package com.funcas.pcloud.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.funcas.pcloud.security.entity.UserVO;
import com.funcas.pcloud.security.mapper.UserMapper;
import com.funcas.pcloud.security.service.IUserService;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author funcas
 * @version 1.0
 * @date 2018年10月23日
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl implements IUserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserVO findUserByLoginName(String loginName) {
        return userMapper.selectOne(new QueryWrapper<UserVO>().eq("username", loginName));
    }

    @Override
    @Cacheable(value = "userAuthorCache", key = "#uid")
    public Set<GrantedAuthority> findUserPermissions(Long uid) {
        List<Map<String,Object>> permList = userMapper.getUserResources(uid);
        Set<GrantedAuthority> grantedAuthorities = Sets.newHashSet();
        for(Map<String,Object> permMap : permList) {
            String perms = (String)permMap.get("permission");
            if(StringUtils.isNotEmpty(perms)){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(perms);
                grantedAuthorities.add(grantedAuthority);
            }
        }
        return grantedAuthorities;
    }
}
